#coding=utf8

import re
import sys
import logging

from cronic import syscron 


def do_delete(content, matchobj, cronfile):
    if not matchobj:
        return False, ''
    else:
        return True, content[:matchobj.start()] + content[matchobj.end():]

def do_update(content, matchobj, cronfile):
    if not matchobj:
        return True, content + '\n'.join(cronfile.generate())
    else:
        return True, content[:matchobj.start()] + '\n'.join(cronfile.generate()) + content[matchobj.end():]


def edit_segment(cronfile, fn):
    segment = cronfile.segment
    content = syscron.read_crontab()
    matchobj = re.search(segment.regex, content, re.S)

    if not matchobj:
        if content.find(segment.begin_line) >= 0:
            logging.getLogger(__name__).error(u'{} 没有结束标志'.format(segment.segment_name))
            sys.exit(-1)
        elif content.find(segment.end_line) >= 0:
            logging.getLogger(__name__).error(u'{} 没有开始标志'.format(segment.segment_name))
            sys.exit(-1)
    
    ok, new_content = fn(content, matchobj, cronfile)
    if ok:
        syscron.write_crontab(new_content)


def delete_segment(cronfile):
    edit_segment(cronfile, do_delete)


def update_segment(cronfile):
    edit_segment(cronfile, do_update)
